import { Component, OnInit } from '@angular/core';
import { RouterService } from './services/router.service';
import { ExtendModule } from './models/module';
import { ModuleService } from './services/module.service';
import 'rxjs/add/operator/do';
import { ServerConfig } from './models/server-config';

@Component({
    selector: 'coeus-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {

    constructor(
        private routerService: RouterService,
        private moduleService: ModuleService
    ) { }

    ngOnInit() {
        this.configInstalledModules();
    }
    // 安装给定的angular module
    async configInstalledModules() {
        const serverConfig: ServerConfig | any = await this.getServerConfig();
        this.moduleService.installedModules$ = this.moduleService.getValidModules(serverConfig).do((res: ExtendModule[]) => {
            if (Array.isArray(res) && res.length) {
                res.forEach(module => {
                    this.registerRoute(module);
                });
            }
        });
    }
    // 给已安装的angular module注册路由
    private registerRoute(module: ExtendModule) {
        this.moduleService.loadModulesBySystemJS(module).then(
            (exports) => {
                this.routerService.createAndRegisterRoute(module, exports, 'plugins');
            },
            err => {
                console.log(err);
            }
        );
    }
    /**
     * 获取服务器地址等相关配置
     */
    private getServerConfig(): Promise<ServerConfig> {
        return new Promise((resolve, reject) => {
            fetch('./assets/config/config.json').then(data => {
                const config = data.json();
                resolve(config);
            }).catch(err => {
                console.log(err);
            });
        });
    }
}
